package com.capinfo.commons.project.web.filter;

import com.capinfo.commons.project.model.security.SystemUser;
import com.capinfo.components.security.model.SecureUser;
import com.capinfo.components.security.service.UserDetailFetcher;
import com.capinfo.framework.service.GeneralService;
import com.capinfo.framework.web.Constants;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class UserFilter implements Filter {

	private UserDetailFetcher userDetailFetcher;
	
	private GeneralService generalService;
	
	private List<String> excludeUrl;
	
	private final PathMatcher pathMatcherByAnt = new AntPathMatcher();

	public UserDetailFetcher getUserDetailFetcher() {
		return userDetailFetcher;
	}

	public void setUserDetailFetcher(UserDetailFetcher userDetailFetcher) {
		this.userDetailFetcher = userDetailFetcher;
	}

	public GeneralService getGeneralService() {
		return generalService;
	}

	public void setGeneralService(GeneralService generalService) {
		this.generalService = generalService;
	}

	public List<String> getExcludeUrl() {
		return excludeUrl;
	}

	public void setExcludeUrl(List<String> excludeUrl) {
		this.excludeUrl = excludeUrl;
	}

	public PathMatcher getPathMatcherByAnt() {
		return pathMatcherByAnt;
	}

	public void destroy() {

	}

	@SuppressWarnings("unchecked")
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		
		String resString = UrlUtils.buildRequestUrl(httpServletRequest);
		
		boolean matched = false;
		for(String url: excludeUrl) {
			
			matched = getPathMatcherByAnt().match(url, resString);
			if( matched ) {
				
				break;
			}
		}
		
		

		if( !matched ) {
			
			SecurityContext securityContext = SecurityContextHolder.getContext();
			
			SecureUser<?, ?> user = (SecureUser<?, ?>) httpServletRequest.getSession().getAttribute(Constants.ADMIN_ATTRIBUTE_KEY);
			
			if ( null == user ) {
				
				if( null != securityContext && null != securityContext.getAuthentication() ) {
					
					String userName = securityContext.getAuthentication().getName();
					
					try {
						user = getUserDetailFetcher().fetch(userName);
						//(User) getGeneralService().getObjectByCriteria(build.build());
						
						//getGeneralService().fetchLazyProperty(user, "roles");
						
						//getGeneralService().getObjectById(SystemUser.class, user.getId());
						SystemUser systemUser = getGeneralService().getObjectById(SystemUser.class, user.getId());
						
						httpServletRequest.getSession().setAttribute(
								Constants.ADMIN_ATTRIBUTE_KEY, systemUser);
					} catch (Exception e) {
						//System.out.println("没有该用户！");
					}
				} else {
					
					httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/logon.jsp");
					return;
				}
			}
		}

		chain.doFilter(request, httpServletResponse);

	}

	public void init(FilterConfig filterConfig) throws ServletException {
	}

}
